/**
 * @description vue.config.js全局配置
 */
// const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
const fs = require('fs')
const path = require('path')
const { publicPath, assetsDir, outputDir, lintOnSave, transpileDependencies, pages, devPort, providePlugin, build7z, buildGzip } = require('./build')
// const vConsolePlugin = require('vconsole-webpack-plugin')
const { version, author, name } = require('./package.json')
const Webpack = require('webpack')
const WebpackBar = require('webpackbar')
const FileManagerPlugin = require('filemanager-webpack-plugin')
const dayjs = require('dayjs')
const dateTime = dayjs().format('YYYY-M-D HH:mm:ss')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['html', 'js', 'css', 'svg']

// let _hasDev = true
let _BuildProject = process.env.BuildProject
let argv = process.argv.splice(2)
if (argv.length > 1) {
  _BuildProject = argv[1]
  // _hasDev = false
}

let _BuildProjectType = process.env.BuildProjectType
if (['pda'].includes(_BuildProject)) {
  _BuildProjectType = 'mobile'
} else {
  _BuildProjectType = 'pc'
}

// production development
process.env.VUE_APP_BuildProjectType = _BuildProjectType
process.env.VUE_APP_BuildProject = _BuildProject
process.env.VUE_APP_ENV = process.env.NODE_ENV
process.env.VUE_APP_TITLE = ''
process.env.VUE_APP_AUTHOR = author
process.env.VUE_APP_RANDOM = `${dayjs()}`
process.env.VUE_APP_UPDATE_TIME = dateTime
process.env.VUE_APP_VERSION = version

const resolve = (dir) => {
  return path.join(__dirname, dir)
}
// console.log('打包项目', _BuildProject)
if (!_BuildProject) {
  console.log('请创建.env文件')
}
let buildProject = _BuildProject || 'login'

// 插件
let _VERSION = `${process.env.NODE_ENV === 'development' ? '\u5f00\u53d1\u9884\u89c8' : '\u7f16\u8bd1\u6253\u5305'
  }[${name}-${buildProject}(${version})]-[${dateTime}]`

let plugins = [
  // new vConsolePlugin({
  //   filter: [], // 需要过滤的入口文件
  //   enable: process.env.VUE_APP_BuildProjectType === 'mobile' ? true : false,
  // }),
  new Webpack.ProvidePlugin(providePlugin),
  new WebpackBar({
    name: _VERSION,
  }),
  // new HardSourceWebpackPlugin(),
  new Webpack.DefinePlugin({
    VERSION: JSON.stringify(_VERSION),
  }),
]
// 独立json
try {
  const TransformJson = require('transform-json-webpack-plugin')
  let serverConfig = require(`./src/project/${buildProject}/serverConfig_${argv[0] === 'serve' ? 'dev' : 'master'}.json`) // 引入独立配置文件

  plugins.push(
    new TransformJson({
      filename: 'serverConfig.json',
      object: serverConfig,
    })
  )
} catch (e) {
  console.log(`${buildProject}-serverConfig.json(无)`)
}

// alias
let getAlias = function () {
  let alias = {}
  const files = fs.readdirSync('src/project/')
  files.forEach((dirName) => {
    alias[`@${dirName}`] = resolve(`src/project/${dirName}`)
  })
  return alias
}

module.exports = {
  publicPath,
  assetsDir,
  transpileDependencies,
  pages: pages(buildProject),
  outputDir: `${outputDir}/${buildProject}`,
  lintOnSave,
  devServer: {
    hot: true,
    port: devPort,
    open: true,
    noInfo: false,
    overlay: {
      warnings: true,
      errors: true,
    },
  },

  configureWebpack() {
    return {
      resolve: {
        alias: {
          '~': resolve('.'),
          '@': resolve('src'),
          '@ve': resolve('src/ve'),
          '@vui': resolve('src/vui/plugins/common/vui'),
          '@project': resolve(`src/project/${buildProject}`),
          '@commonProject': resolve(`src/common/project`),
          ...getAlias(),
        },
      },
      plugins: plugins,
      output: {
        // 把子应用打包成 umd 库格式
        library: `lib_${buildProject}`,
        libraryTarget: 'umd',
        jsonpFunction: `webpackJsonp_${buildProject}`,
      },
      // module: {
      //   rules: [
      //     {
      //       test: /\.wasm$/,
      //       type: 'webassembly/async',
      //     },
      //   ],
      // },
    }
  },

  chainWebpack(config) {
    //config.resolve.alias.set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js')
    config.resolve.symlinks(true)
    config.module.rule('svg').exclude.add(resolve('src/icon'))
    config.module
      .rule('vuiIcon')
      .test(/\.svg$/)
      .include.add(resolve('src/icon'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({ symbolId: 'vui-icon-[name]' })

    config.when(process.env.NODE_ENV === 'development', (config) => {
      if (process.env.BuildProjectType != 'mobile') {
        config.devtool('source-map')
      }
      // config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    })

    config.when(process.env.NODE_ENV === 'production', (config) => {
      config.performance.set('hints', false)

      if (process.env.BuildProjectType != 'mobile') {
        config.devtool('source-map')
      }

      // config.devtool('none')
      // config.optimization.splitChunks({
      //   automaticNameDelimiter: '-',
      //   chunks: 'all',
      //   // cacheGroups: {
      //   //   chunk: {
      //   //     name: 'v-chunk',
      //   //     test: /[\\/]node_modules[\\/]/,
      //   //     minSize: 131072,
      //   //     maxSize: 524288,
      //   //     chunks: 'async',
      //   //     minChunks: 2,
      //   //     priority: 10,
      //   //   },
      //   //   vue: {
      //   //     name: 'vue',
      //   //     test: /[\\/]node_modules[\\/](vue(.*)|core-js)[\\/]/,
      //   //     chunks: 'initial',
      //   //     priority: 20,
      //   //   },
      //   //   elementUI: {
      //   //     name: 'element-plus',
      //   //     test: /[\\/]node_modules[\\/]element-plus(.*)[\\/]/,
      //   //     priority: 30,
      //   //   },
      //   //   // extra: {
      //   //   //   name: 'v-extra',
      //   //   //   test: resolve('src/extra'),
      //   //   //   priority: 40,
      //   //   // },
      //   //   // 根据使用模块抽取公共代码
      //   //   // echarts: {
      //   //   //   name: 'echarts',
      //   //   //   test: /[\\/]node_modules[\\/](echarts|zrender|tslib)[\\/]/,
      //   //   //   priority: 50,
      //   //   // },
      //   // },
      // })
      // config.plugin('banner').use(Webpack.BannerPlugin, [`webpackBanner_${dateTime}`])
      // if (imageCompression) {
      //   config.module
      //     .rule('images')
      //     .use('image-webpack-loader')
      //     .loader('image-webpack-loader')
      //     .options({
      //       bypassOnDebug: true,
      //     })
      //     .end()
      // }
      if (buildGzip) {
        config.plugin('compression').use(CompressionWebpackPlugin, [
          {
            filename: '[path][base].gz[query]',
            algorithm: 'gzip',
            test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
            threshold: 8192,
            minRatio: 0.8,
          },
        ])
      }
      if (build7z) {
        config.plugin('fileManager').use(FileManagerPlugin, [
          {
            events: {
              onEnd: {
                archive: [
                  {
                    source: `./${outputDir}`,
                    destination: `./${outputDir}/${buildProject}_${dayjs().unix()}.zip`,
                  },
                ],
              },
            },
          },
        ])
      }
      // config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    })

    // 对于public文件夹,只拷贝打包项目文件夹资源
    config.plugin('copy').tap((args) => {
      let _args = []
      args.forEach((items) => {
        let _items = []
        items.forEach((item) => {
          item.from = `${item.from}` + '/' + `${buildProject}`
          _items.push(item)
        })
        _args.push(_items)
      })
      return _args
    })
  },

  runtimeCompiler: true,
  productionSourceMap: process.env.BuildProjectType != 'mobile',

  css: {
    requireModuleExtension: true,
    // sourceMap: true,
    loaderOptions: {
      sass: {
        sassOptions: { outputStyle: 'expanded' },
        additionalData(content, loaderContext) {
          const { resourcePath, rootContext } = loaderContext
          const relativePath = path.relative(rootContext, resourcePath)
          if (relativePath.replace(/\\/g, '/') !== 'src/vui/styles/variables/variables.scss')
            return '@use "sass:math";@import "~@/vui/styles/variables/variables.scss";' + content
          return content
        },
      },
    },
  },
}
